package org.noote.libs.tcpip;

import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;

import android.util.Log;

public class IPClient {

	private static final String TAG = "IPClient";

	private Socket mSocket = null;
	private IPClient_ConnectedThread mConnectedThread = null;

	private IPEvent_Client _events = null;
	
	public IPClient(IPEvent_Client events)
	{
		this._events = events; 
	}
	
	public boolean isConnected()
	{
		if(mConnectedThread != null)
			return mConnectedThread.isConnected();
		
		return false;
	}
	
	public boolean connect(String sServerIP, int iPort) {
		try {
			Log.d(TAG, "Connecting...");
			mSocket = new Socket(InetAddress.getByName(sServerIP), iPort);
		} catch (UnknownHostException e) {
			Log.e(TAG, "UnknownHostException " + e.getMessage());
		} catch (IOException e) {
			Log.e(TAG, "IOException " + e.getMessage());
		} catch (Exception e) {
			Log.e(TAG, "Exception " + e.getMessage());
		}
		
		(mConnectedThread = new IPClient_ConnectedThread(mSocket, _events)).start();

		return true;
	}
	
	public boolean close()
	{
		Log.d(TAG, "Close...");
		if(mConnectedThread != null)
		{
			mConnectedThread.close();
			mConnectedThread.interrupt();
			//mConnectedThread.destroy(); ?
		}
		return true;
	}

	public boolean sendMessage(String sMessage) {
		if(mConnectedThread != null)
			return mConnectedThread.sendQueued(sMessage);
		
		return false;
	}
	public boolean sendCommand(String sCmd, String sOp) {
		return sendMessage("#"+sCmd.toLowerCase()+":"+sOp+"$");
	}

}
